package com.eien.phonezwei.utils;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;

import java.lang.reflect.Method;

/**
 * Ap Manager<br/>
 * need permissions:<br/>
 * android.permission.CHANGE_WIFI_STATE
 * android.permission.ACCESS_WIFI_STATE
 * android.permission.WRITE_SETTINGS
 * <br/>Created by honooon on 2017/4/23.
 */
public class ApManager {
    //<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    //<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    //<uses-permission android:name="android.permission.WRITE_SETTINGS" />

    //check whether wifi hotspot on or off
    public static boolean isApOn(Context context) {
        WifiManager wifimanager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        try {
            Method method = wifimanager.getClass().getDeclaredMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (Boolean) method.invoke(wifimanager);
        } catch (Throwable ignored) {
        }
        return false;
    }

    // toggle wifi hotspot on or off
    public static boolean configApState(Context context, boolean turnOn) {
        WifiManager wifimanager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        try {
            // if WiFi is on, turn it off
            if (isApOn(context)) {
                wifimanager.setWifiEnabled(false);
            }
            Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            method.invoke(wifimanager, null, turnOn);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
